package com.siae.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siae.mapper.ItemMapper;
import com.siae.mapper.UserItemMapper;
import com.siae.pojo.Item;
import com.siae.pojo.ItemType;
import com.siae.pojo.UserItem;
import com.siae.pojo.vo.PageResult;
import com.siae.pojo.vo.Result;
import com.siae.service.*;
import com.siae.utils.BizCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {
    private final UserItemService userItemService;

    @Autowired
    public ItemServiceImpl(@Lazy UserItemService userItemService) {
        this.userItemService = userItemService;
    }
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private UserItemMapper userItemMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UniversityService universityService;
    @Autowired
    private ItemTypeService itemTypeService;
    @Autowired
    private UploadFileService uploadFileService;

    // 查询项目全部信息
    @Override
    public Result<PageResult<List<Map>>> getAllItems(Integer currentPage, Integer pageSize, Integer team,Integer student, String name , String type, Integer status) {
        try {
            // 创建分页对象，设置分页参数
            Page<Item> page = new Page<>(currentPage,pageSize);
            Page<Map> pageVo = new Page<>(currentPage,pageSize);
            // 查找项目类别id
            Integer typeId = null;
            if (StringUtils.isNotBlank(type)){
                typeId  = itemTypeService.getAllItemTypes(type,null).getData().get(0).getId();
            }
            // 创建条件对象，设置查询条件参数
            QueryWrapper<Item> wrapper = new QueryWrapper<>();
            wrapper.like(StringUtils.isNotBlank(name),"name",name)
                    .eq(team != null && team != 0,"team",team)
                    .eq(student != null && student != 0,"student",student)
                    .eq(typeId != null && typeId != 0,"type",typeId)
                    .eq(status != null && status != 0,"status",status);
            // 执行查询操作
            this.itemMapper.selectPage(page,wrapper);

            // page.getRecords()获取当前查询到的数据
            if (page.getRecords().size() > 0){
                PageResult<List<Map>> pageResult = new PageResult<>();
                /**
                 * page中的records是List<Item>,无法改变ItemVo中的属性，所以使用stream流
                 * */
                List<Map> mapVos = page.getRecords().stream()
                        .map(item -> {
                            Map itemMap = getItemMap(item);
                    return itemMap;
                }).collect(Collectors.toList());
                pageVo.setRecords(mapVos);
                pageResult.setTotal(page.getTotal());
                pageResult.setData(pageVo.getRecords());
                return Result.success(BizCode.SUCCESS,pageResult);
            }else {
                return Result.fail(BizCode.FAIL);
            }
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询项目信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
    private String getUserName(Integer id){
        return userService.getUserById(id).getData().getUserName();
    }
    private String getFileName(Integer id){
        return uploadFileService.getFilePath(id,null).getData().get(0).getFilePath();
    }
    public String getStatusStr(Integer status) {
        if (status != null) {
            switch (status) {
                case 0:
                    return "草稿";
                case 1:
                    return "已提交";
                case 2:
                    return "审核中";
                case 3:
                    return "已通过";
                case 4:
                    return "已驳回";
                case 5:
                    return "已完成";
            }
        }
        return null;
    }
    private Map getItemMap(Item item){
        Map itemMap = new HashMap<>();
        itemMap.put("id",item.getId());
        itemMap.put("name",item.getName());
        itemMap.put("image",getFileName(item.getImage()));
        itemMap.put("type",itemTypeService.getItemTypeById(item.getType()).getData().getName());
        itemMap.put("student",getUserName(item.getStudent()));
        itemMap.put("team",userItemService.getItemById(item.getTeam()).getData().getName());
        itemMap.put("teacher",getUserName(item.getTeacher()));
        itemMap.put("college",universityService.getUniversityById(item.getCollege()).getData().getUniversityName());
        itemMap.put("files",uploadFileService.getUploadFileById(item.getFiles()).getData().getFileName());
        itemMap.put("status",getStatusStr(item.getStatus()));
        itemMap.put("createdAt",item.getCreatedAt());
        itemMap.put("updatedAt",item.getUpdatedAt());
        itemMap.put("isDel",item.getIsDel());
        return itemMap;
    }

    // 根据id查询项目信息
    @Override
    public Result<Map> getItemById(Integer id) {
        try{
            Item item = itemMapper.selectById(id);
            Map itemMap = getItemMap(item);
            return Result.success(BizCode.SUCCESS,itemMap);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询项目信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<Item> getItemByName(String name) {
        try{
            QueryWrapper<Item> wrapper = new QueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(name),"name",name);
            Item item = itemMapper.selectOne(wrapper);
            return Result.success(BizCode.SUCCESS,item);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询项目id失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
    private Integer getUserId(String userName){
        return userService.getUserByName(userName).getData().getId();
    }
    private Integer getFileId(String filePath){

            return uploadFileService.getFilePath(null,filePath).getData().get(0).getId();


    }
    private Integer getItemTypeId(String name){
        ItemType data = itemTypeService.getItemTypeByName(name).getData();
        if (data != null){
            return data.getId();
        }
        return null;
    }

    @Override
    public Result addItem(Map dateMap) {
        try{
            Item itemDate = getItemByName(dateMap.get("name").toString()).getData();
            if (itemDate != null && itemDate.getId() != null){
                return Result.fail(BizCode.NAME_ALREADY_EXIST);
            }
            Item item = new Item();
            item.setId(null);
            item.setName(dateMap.get("name").toString());
            item.setImage(getFileId(dateMap.get("image").toString()));
            item.setType(Integer.parseInt(dateMap.get("type").toString()));
            item.setStudent(getUserId(dateMap.get("student").toString()));
            // 判断选择的团队的项目信息是否存在
            Result<UserItem> team = userItemService.getUserItemByName(dateMap.get("team").toString());
            UserItem data = team.getData();
            String UserItemName = data.getName()+new Date().getTime();
            Map map = new HashMap<>();
            map.put("id",data.getId());
            map.put("name",UserItemName);
            map.put("userId",data.getUserId());
            map.put("userIdOne",data.getUserIdOne());
            map.put("userIdTwo",data.getUserIdTwo());
            map.put("userIdThree",data.getUserIdThree());
            map.put("itemId","");
            if (team.getData().getItemId() != null){
                map.put("addType",1);
                Result result = userItemService.addItem(map);
                if (result.getCode() == 2000){
                    item.setTeam(userItemService.getUserItemByName(map.get("name").toString()).getData().getId());
                } else {
                    item.setTeam(null);
                }
            }
            item.setTeacher(getUserId(dateMap.get("teacher").toString()));
            item.setCollege(Integer.parseInt(dateMap.get("college").toString()));
            item.setFiles(getFileId(dateMap.get("files").toString()));
            item.setStatus(0);
            item.setCreatedAt(new Date());
            item.setUpdatedAt(new Date());
            item.setIsDel(0);
            int i = itemMapper.insert(item);
            if (i > 0){
                Integer id1 = getItemByName(dateMap.get("name").toString()).getData().getId();
                // 创建项目成功时，更新团队项目id
                QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
                wrapper.eq(StringUtils.isNotBlank(map.get("name").toString()),"name",map.get("name").toString());
                Integer userItemId = userItemMapper.selectOne(wrapper).getId();
                UserItem userItem = new UserItem();
                userItem.setId(userItemId);
                userItem.setItemId(id1);
                userItemMapper.updateById(userItem);
                // 反过来更新项目团队id
                item.setId(id1);
                item.setTeam(userItemService.getUserItemByName(map.get("name").toString()).getData().getId());
                itemMapper.updateById(item);
            }
            return Result.success(BizCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            log.error("添加项目信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result updateItem(Map dateMap) {
        try{
            Item item = new Item();
            item.setId(Integer.parseInt(dateMap.get("id").toString()));
            item.setName(dateMap.get("name").toString());
            item.setImage(getFileId(dateMap.get("image").toString()));
            item.setType(getItemTypeId(dateMap.get("type").toString()));
            item.setStudent(getUserId(dateMap.get("student").toString()));
            item.setTeam(userItemService.getUserItemByName(dateMap.get("team").toString()).getData().getId());
            item.setTeacher(getUserId(dateMap.get("teacher").toString()));
            item.setCollege(universityService.getUniversityByName(dateMap.get("college").toString()).getData().get(0).getId());
            if(Integer.parseInt(dateMap.get("status").toString()) == 2){
                item.setFiles(uploadFileService.getUploadFileByName(dateMap.get("files").toString()).getData().getId());
            }else {
                item.setFiles(getFileId(dateMap.get("files").toString()));
            }
            item.setStatus(Integer.parseInt(dateMap.get("status").toString()));
            item.setUpdatedAt(new Date());
            item.setIsDel(Integer.parseInt(dateMap.get("isDel").toString()));
            itemMapper.updateById(item);
            return Result.success(BizCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改项目信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result deleteItem(Integer id) {
        try{
            String string = userItemService.getAllItems(null, null, id).getData().get(0).get("id").toString();
            int i = itemMapper.deleteById(id);
            if (i > 0){
                userItemMapper.deleteById(Integer.parseInt(string));
            }
            return Result.success(BizCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除项目信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
}
